package com.hzsai.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * @author: hzsai
 * @date : 2020/3/19/ 1:31
 **/
@Component
public class CustomTaskScheduler {

    private ScheduledFuture<?> future;

    private Runnable runnable;

    private long delay;

    @Autowired
    @Qualifier("threadxPoolTaskScheduler")
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    @PostConstruct
    public void postConstruct() {
        assert threadPoolTaskScheduler != null;
    }

    public void scheduleWithFixedDelay(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.delay = delay;
    }

    public void start() {
        future = threadPoolTaskScheduler.scheduleWithFixedDelay(runnable, delay);
    }

    public void stop() {
        future.cancel(false);
    }

    public void schedule(Runnable runnable) {
        threadPoolTaskScheduler.schedule(runnable, new Date());
    }
}
